package com.ruoyi.common.utils.xml;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class XmlUtil {
    //https://blog.csdn.net/qq_20161461/article/details/111664807
    //https://blog.csdn.net/qq_43548590/article/details/117445503

    private static XmlMapper xmlMapper = new XmlMapper();
    private static ObjectMapper objectMapper = new ObjectMapper();

    private static XmlMapper getXmlMapper() {
        xmlMapper.setDefaultUseWrapper(false);
        //字段为null，自动忽略，不再序列化
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //XML标签名:使用骆驼命名的属性名，
        xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
        //设置转换模式
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
//        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 设置为 false
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        return xmlMapper;
    }

    private static ObjectMapper getObjectMapper() {

        return objectMapper;
    }

    public static String toXml(Object value) {
        try {
            String xml = getXmlMapper().writeValueAsString(value);
            return xml;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T parseObject(String str,Class<T> valueType) {
        try {
//            getObjectMapper().readValue(str,valueType);
            return getXmlMapper().readValue(str,valueType);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
